﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Reflection;
using System.Collections;
using System.Xml;
using System.IO;

public partial class TestToolBox : System.Web.UI.Page
{
    ServerObject mServerObject = null;
    string mTableName = "TestToolBox";
    public string mNamePanel = "Test ToolBox";

    DataTable mConfigTable = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (mServerObject == null) mServerObject = new ServerObject();
        if (Utils.AutentificatedUser)
        {
            //get csvSelect from ConfigPanel by TableName
            mConfigTable = mServerObject.GetConfigPanelByPanelName(mNamePanel);

            if (!IsPostBack)
            {
                ShowPanel(listPanel.ID);
            }

            switch (Request.Params.Get("__EVENTTARGET"))
            {
                case "newSave":
                    newSaveButton_Click(Request.Params.Get("__EVENTARGUMENT"));
                    break;

                case "newCancel":
                    //Request.Params.Get("__EVENTARGUMENT");
                    this.newCancelButton_Click();
                    break;
            }
        }
        else
        {
            ShowPanel(string.Empty);
        }
    }

    private void ShowPanel(string panelName)
    {
        #region Hide panels

        emptyPanel.Visible = false;
        listPanel.Visible = false;

        newPanel.Visible = false;
        editPanel.Visible = false;

        #endregion Hide panels

        try
        {
            #region Get Panel Name

            switch (panelName)
            {
                case "listPanel":
                    listPanel.Visible = true;

                    FillListGridView();

                    Utils.EnableButtons(mConfigTable, addNewButton, editButton, deleteButton, listGridView);

                    break;

                case "newPanel":
                    newPanel.Visible = true;
                    newPanel.Controls.Add(Utils.GetNewPanel(mTableName, mNamePanel, Utils.ModuleMain()));
                    break;

                case "editPanel":
                    editPanel.Visible = true;
                    {
                        DataTable genderList = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.GenderList);
                        Utils.FillSelector(editGenDDL, genderList, "Name", "Code");
                    }

                    break;

                case "emptyPanel":
                    emptyPanel.Visible = true;
                    break;

                default:
                    emptyPanel.Visible = true;
                    break;
            }

            #endregion Get Panel Name

        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }

    #region ListPanel

    #region ListGridView

    protected void FillListGridView()
    {
        DataTable arrayTable = Utils.GetArrayTableForSelectOperation(mTableName, mNamePanel);

        string csvColumns = Utils.GetCSVColumnFromArrayTable(arrayTable);

        string filterSelect = string.Empty; // " isB = 0";
        DataTable sourceTable = mServerObject.UniversalGetFromSingleTable(mTableName, csvColumns, filterSelect);

        if (sourceTable != null && !IsPostBack)
        {
            Utils.GetColumnsForGridView(listGridView, arrayTable);
        }

        listGridView.DataSource = sourceTable;
        listGridView.DataBind();

        Utils.SetHiddenFieldValue(listGridView, sourceTable);
    }

    protected void listGridView_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
    {
        listGridView.PageIndex = e.NewPageIndex;
        FillListGridView();
    }

    protected void listGridView_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

            for (int i = 0; i < e.Row.Cells.Count - 1; i++)
            {
                e.Row.Cells[i].Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.listGridView, "Select$" + e.Row.RowIndex);
            }
        }
    }

    protected void headerCheckBoxID_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox headerCheckBox = listGridView.HeaderRow.FindControl("headerCheckBoxID") as CheckBox;
        if (headerCheckBox != null)
        {
            for (int indexRow = 0; indexRow < listGridView.Rows.Count; indexRow++)
            {
                CheckBox listCheckBox = listGridView.Rows[indexRow].Cells[0].FindControl("listCheckBoxID") as CheckBox;
                listCheckBox.Checked = headerCheckBox.Checked;
            }
        }
    }

    #endregion ListGridView

    #region buttonGeneral

    protected void newButton_Click(object sender, EventArgs e)
    {
        ShowPanel(newPanel.ID);
    }

    protected void deleteButton_Click(object sender, EventArgs e)
    {
        try
        {
            string csvIndexID = string.Empty;

            for (int indexRow = 0; indexRow < listGridView.Rows.Count; indexRow++)
            {
                CheckBox selectedCheckBox = listGridView.Rows[indexRow].FindControl("listCheckBoxID") as CheckBox;
                if (selectedCheckBox.Checked)
                {
                    if (csvIndexID.Length > 0)
                    {
                        csvIndexID += ", ";
                    }

                    HiddenField indexIDHiddenField = listGridView.Rows[indexRow].FindControl("indexIDHiddenField") as HiddenField;
                    csvIndexID += indexIDHiddenField.Value;
                }
            }

            if (!string.IsNullOrEmpty(csvIndexID))
            {
                string whereCondition = "plancontID IN (" + csvIndexID + ") ";

                if (mServerObject.UniversalMarkForDeleteFromValue(mTableName, whereCondition))
                {
                    ShowPanel(listPanel.ID);
                }
                else
                {
                    Utils.InfoText(this, "Atentie", "Sunt date care nu au fost sterse. Verificati conectiunea cu internet.");
                }
            }
            else
            {
                Utils.InfoText(this, "Atentie", "Nu au fost selectate nici un rind!");
            }
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie", ex.Message);
        }
    }

    protected void refreshButton_Click(object sender, EventArgs e)
    {
        ShowPanel(listPanel.ID);
    }

    protected void editButton_Click(object sender, EventArgs e)
    {
        //ClearEditPersonPanel();
        //ShowPanel(editPanel.ID);

        //GridViewRow row = personsGridView.SelectedRow;
        //int indexCell = 0;

        //string personID = row.Cells[indexCell++].Text;
        //if (!personID.Equals("&nbsp;"))
        //    editPersonIDHiddenField.Value = personID;

        //string personNume = row.Cells[indexCell++].Text;
        //if (!personNume.Equals("&nbsp;"))
        //    editNumeTextBox.Text = personNume;

        //editPrenumeTextBox.Text = row.Cells[indexCell++].Text;

        //if (!row.Cells[indexCell++].Text.Equals(string.Empty))
        //{
        //    ListItem genItem = new ListItem(row.Cells[indexCell].Text, row.Cells[indexCell].Text);
        //    if (editGenDDL.Items.Contains(genItem))
        //    {
        //        editGenDDL.SelectedValue = row.Cells[indexCell].Text;
        //    }
        //}

        //string adresa = row.Cells[indexCell++].Text;
        //if (!adresa.Equals("&nbsp;"))
        //    editAdresaTextBox.Text = adresa;

        //string telFix = row.Cells[indexCell++].Text;
        //if (!telFix.Equals("&nbsp;"))
        //    editTelefonFixTextBox.Text = telFix;

        //string telGsm = row.Cells[indexCell++].Text;
        //if (!telGsm.Equals("&nbsp;"))
        //    editTelefonGSMTextBox.Text = telGsm;

        //string email = row.Cells[indexCell++].Text;
        //if (!email.Equals("&nbsp;"))
        //    editEmailTextBox.Text = email;
    }

    #endregion buttonGeneral

    #endregion ListPanel

    #region NewPanel

    protected void newSaveButton_Click(string listArgument)
    {
        //Hashtable insertHashTable = Utils.newSaveButton(listArgument, mTableName, mNamePanel);

        if (mServerObject.UniversalInsertFromValue(listArgument, mTableName, mNamePanel))
        {
            ShowPanel(listPanel.ID);
        }
        else
        {
            Utils.InfoText(this, "Atentie", "Valorile din formularul " + mNamePanel + " - nu a fost salvat. Verificati conectiunea cu internet ");
        }
    }

    protected void newCancelButton_Click()
    {
        ShowPanel(listPanel.ID);
    }

    #endregion NewPanel

    #region EditPanel

    protected void editSaveButton_Click(object sender, EventArgs e)
    {
        int personID = 0;
        int.TryParse(editPersonIDHiddenField.Value, out personID);

        string nume = editNumeTextBox.Text.Trim();
        string prenume = editPrenumeTextBox.Text.Trim();

        int genID = 0;
        int.TryParse(editGenDDL.SelectedValue.ToString(), out genID);

        string adresa = editAdresaTextBox.Text.Trim();
        string telefonFix = editTelefonFixTextBox.Text.Trim();
        string telefonGSM = editTelefonGSMTextBox.Text.Trim();
        string email = editEmailTextBox.Text.Trim();

        string csvSet = string.Empty;

        csvSet += "nume ='" + nume + "' ";
        csvSet += ", prenume ='" + prenume + "'";
        csvSet += ", genID=" + genID + " ";
        csvSet += ", adresa='" + adresa + "' ";
        csvSet += ", telefonFix ='" + telefonFix + "' ";
        csvSet += ", telefonGSM ='" + telefonGSM + "' ";
        csvSet += ", email ='" + email + "' ";

        string whereCondition = " personID = " + personID.ToString();

        if (mServerObject.UniversalUpdateFromValue(mTableName, csvSet, whereCondition))
        {
            ShowPanel(listPanel.ID);
        }
        else
        {
            Utils.InfoText(this, "Atentie", " { " + nume + " " + prenume + " } - nu a fost salvat. Verificati conectiunea cu internet ");
        }
    }

    protected void editCancelButton_Click(object sender, EventArgs e)
    {
        ShowPanel(listPanel.ID);
    }

    #endregion EditPanel

    protected void testXMLButton_Click(object sender, EventArgs e)
    {
        #region Test Fisier 2
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode docNodeName = xmlDoc.CreateXmlDeclaration("1.0", "ISO-8859-1", null);
            xmlDoc.AppendChild(docNodeName);

            XmlElement rootNode = xmlDoc.CreateElement("CATALOG");
            xmlDoc.AppendChild(rootNode);

            XmlElement headerNode = xmlDoc.CreateElement("HEADER");
            rootNode.AppendChild(headerNode);

            headerNode.AppendChild(XMLUtility.CreateXmlNode(xmlDoc, "H01", "S.E.C.A. Cartea"));
            headerNode.AppendChild(XMLUtility.CreateXmlNode(xmlDoc, "H02", "or.Chisinau, b-dul Stefan cel Mare 180"));
            headerNode.AppendChild(XMLUtility.CreateXmlNode(xmlDoc, "H03", "1003600000763"));
            headerNode.AppendChild(XMLUtility.CreateXmlNode(xmlDoc, "H04", "0503374"));
            headerNode.AppendChild(XMLUtility.CreateXmlNode(xmlDoc, "H05", "2627"));
            headerNode.AppendChild(XMLUtility.CreateXmlNode(xmlDoc, "H06", "30.7.2013"));
            headerNode.AppendChild(XMLUtility.CreateXmlNode(xmlDoc, "H07", "11:2:29"));
            headerNode.AppendChild(XMLUtility.CreateXmlNode(xmlDoc, "H08", "30 iulie 2013"));

            xmlDoc.Save(Server.MapPath("~/Files/data_cmr_client_header.xml"));
        }
        #endregion Test Fisier 2

        #region Test Fisier 1
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode docNodeName = xmlDoc.CreateXmlDeclaration("1.0", "ISO-8859-1", null);
            xmlDoc.AppendChild(docNodeName);

            XmlElement rootNode = xmlDoc.CreateElement("CATALOG");
            xmlDoc.AppendChild(rootNode);

            int citeProducteVreai = 5;
            int citeProprietatiVreai = 20;

            for (int p = 0; p < citeProducteVreai; p++)
            {
                XmlElement productNode = xmlDoc.CreateElement("PRODUCT");
                rootNode.AppendChild(productNode);

                for (int i = 0; i < citeProprietatiVreai; i++)
                {
                    productNode.AppendChild(XMLUtility.CreateXmlNode(xmlDoc, "COL" + (i + 1).ToString(), "Value of node :" + (i + 1).ToString()));
                }
            }

            xmlDoc.Save(Server.MapPath("~/Files/data_cmr_client_table.xml"));         
        }

        #endregion Test Fisier 1
    }
}